<template>
    <div>
        <a-space :size="10">
            <EsSearchHostAndIndexComponent v-model:es-host-value="esHostValue" v-model:es-index-value="esIndexValue" />
            <a-button type="link" @click="openHighLevelSearchModal"> 查询条件 </a-button>
            <a-button type="primary" @click="onSearch" :loading="searchBtnLoading">
                <template #icon>
                    <SearchOutlined />
                </template>
                查询
            </a-button>
            <a-button type="dashed" @click="openSelectShowFieldsModal">选择显示字段</a-button>
        </a-space>
    </div>
    <a-divider style="background-color: rgb(231, 231, 231); height: 1px" dashed />
    <div style="margin-top: 5px" v-show="tableData.length > 0">
        <a-space>
            <a-dropdown>
                <template #overlay>
                    <a-menu @click="handleMenuClick">
                        <a-menu-item :key="1">添加Deepl翻译</a-menu-item>
                        <a-menu-item :key="2">添加AI改写</a-menu-item>
                        <a-menu-item :key="3">添加AI生成</a-menu-item>
                        <a-menu-item :key="4">添加奶盘伪原创</a-menu-item>
                        <a-menu-item :key="5">添加搜狗伪原创</a-menu-item>
                        <a-menu-item :key="6">添加标题伪原创</a-menu-item>
                        <a-menu-item :key="7">添加百度Site采集</a-menu-item>
                    </a-menu>
                </template>
                <a-button type="primary">
                    工具箱
                    <DownOutlined />
                </a-button>
            </a-dropdown>
            <a-button type="link" @click="copySearchBody" style="color: #52c41a">复制搜索体</a-button>
            <a-button type="link" @click="esExportHandleVisible = true">导出数据</a-button>
            <a-button v-show="updateAndDeleteIsShow" style="color: #faad14" type="link" @click="esUpdateHandleVisible = true"
                >修改数据</a-button
            >
            <a-button
                v-show="updateAndDeleteIsShow"
                @click="esDeleteHandleVisible = true"
                type="dashed"
                danger
                v-if="useAdminShow()"
                >删除数据</a-button
            >
        </a-space>
    </div>
    <a-spin tip="Loading..." :spinning="tableLoading" :style="spinStyle">
        <a-table
            v-show="tableData.length > 0"
            :columns="tableColumns"
            :data-source="tableData"
            @resizeColumn="handleResizeColumn"
            style="margin-top: 10px"
            sticky
            @change="handleTableChange"
            :scroll="{ x: tableScrollX }"
            :rowKey="createRowKey"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            bordered
            :pagination="false"
            size="small"
            class="table"
        >
            <template #bodyCell="{ column, text }">
                <template v-if="column.dataIndex === 'name'">
                    <a>{{ text }}</a>
                </template>
            </template>
        </a-table>
        <br />

        <a-row justify="center" v-if="total > 10">
            <a-pagination
                v-model:current="current"
                v-model:pageSize="pageSize"
                show-quick-jumper
                :page-size-options="['10', '20', '50', '100', '250', '500', '750', '1000']"
                :total="total"
                @change="pageChange"
                :show-total="(total: number) => `总计 ${total} 项`"
            />
        </a-row>
    </a-spin>
    <EsHighLevelSearchComponent
        v-model:visible="highLevelSearchVisible"
        v-model:query-bool="esQueryBool"
        :es-host="esHostValue"
        :es-index="esIndexValue"
        :mustModeMap="mustModeMap"
    >
    </EsHighLevelSearchComponent>
    <SelectShowTableFieldsComponent
        v-model:visible="showFieldsModalVisible"
        v-model:fields="showFields"
        :es-host="esHostValue"
        :es-index="esIndexValue"
        :key="esIndexValue"
    />
    <UpdateDataHandleComponent
        v-model:visible="esUpdateHandleVisible"
        :fields="showFields"
        :es-host="esHostValue"
        :es-index="esIndexValue"
        :key="esIndexValue"
    />
    <DeleteDataHandleComponent
        v-model:visible="esDeleteHandleVisible"
        :es-host="esHostValue"
        :es-index="esIndexValue"
        :key="esIndexValue"
    />
    <ExportDataHandleComponent
        v-model:visible="esExportHandleVisible"
        :fields="showFields"
        :es-host="esHostValue"
        :es-index="esIndexValue"
        :key="esIndexValue"
    />
    <AddDeeplTaskComponent v-model:visible="addDeeplTaskVisible" :es-host="esHostValue" :es-index="esIndexValue">
    </AddDeeplTaskComponent>
    <AddAiReWirteTaskComponent v-model:visible="addAiRewriteTaskVisible" :es-host="esHostValue" :es-index="esIndexValue">
    </AddAiReWirteTaskComponent>
    <AddNaiPanOrSogouWycComponent
        v-model:visible="naiPanOrSogouWycVisible"
        :es-host="esHostValue"
        :es-index="esIndexValue"
        :wycType="wycType"
    ></AddNaiPanOrSogouWycComponent>
    <AddAIGenerateTaskComponent
        v-model:visible="addAiGenerateTaskVisible"
        :es-host="esHostValue"
        :es-index="esIndexValue"
    ></AddAIGenerateTaskComponent>
    <AddTitleWycTaskComponent
        v-model:visible="titleWycVisible"
        :es-host="esHostValue"
        :es-index="esIndexValue"
    ></AddTitleWycTaskComponent>
    <AddBaiduSiteTaskComponent v-model:visible="baiduSiteTaskVisible"></AddBaiduSiteTaskComponent>
</template>

<script lang="ts" setup>
    import { SearchOutlined, DownOutlined } from "@ant-design/icons-vue";
    import { useAdminShow, useUserName } from "@/hooks/useCommon";
    import { message, type TableColumnsType, type TableProps } from "ant-design-vue";
    import SelectShowTableFieldsComponent from "@/tsx/esCommonSearch/SelectShowTableFields";
    import EsHighLevelSearchComponent from "@/tsx/esCommonSearch/EsHighLevelSearch";
    import EsSearchHostAndIndexComponent from "@/tsx/esCommonSearch/EsSearchHostAndIndex";
    import AddAIGenerateTaskComponent from "@/tsx/esCommonSearch/AddAIGenerateTask";
    import DeleteDataHandleComponent from "@/tsx/esCommonSearch/DeleteDataHandle";
    import UpdateDataHandleComponent from "@/tsx/esCommonSearch/UpdateDataHandle";
    import ExportDataHandleComponent from "@/tsx/esCommonSearch/ExportDataHandle";
    import AddDeeplTaskComponent from "@/tsx/esCommonSearch/AddDeeplTask";
    import AddAiReWirteTaskComponent from "@/tsx/esCommonSearch/AddAiReWirteTask";
    import AddNaiPanOrSogouWycComponent from "@/tsx/esCommonSearch/AddNaiPanOrSogouWyc";
    import AddTitleWycTaskComponent from "@/tsx/esCommonSearch/AddTitleWycTask";
    import AddBaiduSiteTaskComponent from "@/tsx/esCommonSearch/AddBaiduSiteTask";
    import { esSearchActionApi } from "@/api/esArticle";
    import { useTableColumns } from "@/hooks/useEsCommonSearch";
    import { useSpinLoadingState } from "@/hooks/useCommon";
    import { useClipboard } from "@vueuse/core";
    const { spinStyle, viewLoading: tableLoading } = useSpinLoadingState();
    const esHostValue = ref("http://192.168.1.92:9200");
    const $route = useRoute();
    const esQueryBool = reactive<EsQueryBoolType>({ must: [], must_not: [], should: [] });
    const routeQuery = toRef($route, "query");
    const mustModeMap = reactive<MustModeMap>({
        must: { conditions: [] },
        must_not: { conditions: [] },
        should: { conditions: [] }
    });
    const updateAndDeleteIsShow = ref(true);
    // 显示表格字段的对话框
    const showFieldsModalVisible = ref(false);
    // 收集到的表格字段
    const showFields = ref<Array<string>>(["title", "content"]);
    const tableScrollX = computed(() => showFields.value.length * 200);
    // 文章索引
    const esIndexValue = ref("");
    // 自定义index
    const searchBtnLoading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
    // 表格行key
    const createRowKey = (item: any) => item._id;
    const selectedRowKeys = ref<Array<string>>([]);
    const onSelectChange = (keys: any) => {
        selectedRowKeys.value = keys;
    };
    function handleResizeColumn(w:number, col:Record<string,any>) {
        col.width = w;
    }

    // 分页
    const pageSize = ref(10);
    // 当前页
    const current = ref(1);
    // 存储每次搜索后返回的query体
    const esSearchQuery = ref({});
    provide("esQuery", esSearchQuery);
    provide("esIds", selectedRowKeys);
    watch(esHostValue, (v) => {
        current.value = 1;
        if (v.includes("192.168.1.109") && useUserName() != "lcw") {
            updateAndDeleteIsShow.value = false;
        } else if (esHostValue.value.includes("192.168.1.94") && useUserName() != "lcw") {
            updateAndDeleteIsShow.value = false;
        } else {
            updateAndDeleteIsShow.value = true;
        }
    });
    // 搜索事件回调
    const onSearch = () => {
        if (!esIndexValue.value && !esIndexValue.value) {
            message.warning("请输入索引或选择EsHost");
            return;
        }
        // 搜索
        searchBtnLoading.value = true;
        const parmas: EsSearchActionParmas = {
            host: esHostValue.value,
            index: esIndexValue.value,
            size: pageSize.value,
            page: current.value,
            show_fields: showFields.value,
            query_bool: esQueryBool,
            ...sortObj
        };
        tableLoading.value = true;
        esSearchActionApi(parmas)
            .then((res) => {
                if (res.data.code === 200) {
                    tableData.value = res.data.data;
                    total.value = res.data.total;
                    esSearchQuery.value = res.data.query;
                    // @ts-ignore
                    tableColumns.value = useTableColumns(showFields.value, esHostValue.value, esIndexValue.value);
                } else {
                    message.error("查询失败!");
                }
                tableLoading.value = false;
                searchBtnLoading.value = false;
            })
            .catch(() => {
                message.error("搜索失败,请查看索引是否存在!");
                tableLoading.value = false;
                searchBtnLoading.value = false;
            });
    };
    const copySearchBody = () => {
        const source = ref(JSON.stringify(esSearchQuery.value));
        if (navigator.clipboard) {
            const { copy } = useClipboard({ source });
            copy();
        } else {
            const input = document.createElement("input");
            input.setAttribute("value", source.value);
            document.body.appendChild(input);
            input.select();
            document.execCommand("copy");
            document.body.removeChild(input);
        }
        message.success("复制成功");
    };
    // 控制高级搜索的对话框隐藏显示
    const highLevelSearchVisible = ref(false);
    // 打开高级搜索对话框输入其他条件
    const openHighLevelSearchModal = () => {
        if (!esHostValue.value || !esIndexValue.value) {
            message.error("请输入索引或选择EsHost");
            return;
        }
        highLevelSearchVisible.value = true;
    };
    // 当前页变化
    const pageChange = (pageNumber: number) => {
        current.value = pageNumber;
        onSearch();
    };
    // 排序对象
    const sortObj = {
        sort_field: "",
        order: ""
    };
    // 表格排序发生改变
    const handleTableChange: TableProps["onChange"] = (pag, filters: any, sorter: any) => {
        if (sorter.order) {
            sortObj.order = sorter.order.slice(0, sorter.order.length - 3);
            sortObj.sort_field = sorter.field;
        } else {
            sortObj.order = "";
        }
        onSearch();
    };
    const openSelectShowFieldsModal = () => {
        if (!esIndexValue.value || !esHostValue.value) {
            message.error("请输入索引或选择EsHost");
            return;
        }
        showFieldsModalVisible.value = true;
    };
    onMounted(() => {
        if (routeQuery.value.host) {
            esHostValue.value = routeQuery.value.host as string;
            esIndexValue.value = routeQuery.value.index as string;
            const fields = (routeQuery.value.fields as string) || "[]";
            const arr = JSON.parse(fields) 
            if(arr.length){
                showFields.value = arr
            }
            setTimeout(onSearch,500)
        }

    });
    watch(esIndexValue,()=>{
        sortObj.sort_field = ""
        current.value = 1;
    })
    // 通过 showFields.value 计算出 tableColumns
    const tableColumns = ref<TableColumnsType>([]);
    // 导出,删除,更新 控制的Modal
    const esExportHandleVisible = ref(false);
    const esDeleteHandleVisible = ref(false);
    const esUpdateHandleVisible = ref(false);
    // deepl 伪原创
    const addDeeplTaskVisible = ref(false);
    // ai改写任务
    const addAiRewriteTaskVisible = ref(false);
    // ai生成
    const addAiGenerateTaskVisible = ref(false);
    // 奶盘或搜狗伪原创
    const naiPanOrSogouWycVisible = ref(false);
    const wycType = ref(0);
    // 标题伪原创
    const titleWycVisible = ref(false);
    // 百度Site 采集
    const baiduSiteTaskVisible = ref(false);
    // 点击其他操作 后任意一项的回调
    const handleMenuClick = (e: any) => {
        if (e.key === 1) {
            // 添加deepl伪原创
            addDeeplTaskVisible.value = true;
        }
        if (e.key === 2) {
            // 添加ai改写
            addAiRewriteTaskVisible.value = true;
        }
        if (e.key === 3) {
            // 添加ai生成
            addAiGenerateTaskVisible.value = true;
        }
        if (e.key === 4 || e.key === 5) {
            naiPanOrSogouWycVisible.value = true;
            wycType.value = e.key === 4 ? 6 : 8;
        }
        if (e.key === 6) {
            titleWycVisible.value = true;
        }
        if (e.key === 7) {
            baiduSiteTaskVisible.value = true;
        }
    };
    watch(
        () => routeQuery.value.must,
        () => {
            const must = (routeQuery.value.must as string) || "[]";
            mustModeMap.must.conditions = JSON.parse(must);
            
        },
        {
            immediate: true
        }
    );
    provide("esHost", esHostValue);
    provide("esIndex", esIndexValue);
</script>

<style scoped lang="scss"></style>
